#include <iostream>
#include <memory>
#include <algorithm> // 用于std::uninitialized_copy

using namespace std;

template<typename T> 
class Vector 
{ 
public:     
    using iterator = T *;

    iterator begin() const { return _start; }
    iterator end() const { return _finish; }

    Vector();     
    ~Vector();          
    void push_back(const T &);      
    void pop_back();         
    int size() const;     
    int capacity() const; 
private:     
    void reallocate(); // 重新分配内存，动态扩容
private:         
    static std::allocator<T> _alloc;          
    T *_start;        // 指向数组中的第一个元素     
    T *_finish;       // 指向最后一个实际元素之后的元素     
    T *_end_of_storage; // 指向数组末尾之后的位置 
};

template<typename T> 
std::allocator<T> Vector<T>::_alloc;

template<typename T> 
Vector<T>::Vector() : _start(nullptr), _finish(nullptr), _end_of_storage(nullptr) {}

template<typename T> 
Vector<T>::~Vector() {
    if (_start) {
        // 销毁所有已构造的元素
        for (T* p = _start; p != _finish; ++p) {
            _alloc.destroy(p);
        }
        _alloc.deallocate(_start, capacity());
    }
}

template<typename T> 
void Vector<T>::push_back(const T &value) {
    if (size() == capacity()) {
        reallocate();
    }
    _alloc.construct(_finish++, value);
}

template<typename T> 
void Vector<T>::pop_back() {
    if (size() > 0) {
        --_finish;
        _alloc.destroy(_finish);
    }
}

template<typename T> 
int Vector<T>::size() const { return _finish - _start; }

template<typename T> 
int Vector<T>::capacity() const { return _end_of_storage - _start; }

template<typename T> 
void Vector<T>::reallocate() {
    size_t oldCapacity = capacity();
    size_t newCapacity = oldCapacity ? 2 * oldCapacity : 1;
    size_t oldSize = size();

    T* newStart = _alloc.allocate(newCapacity);
    T* newFinish = std::uninitialized_copy(_start, _finish, newStart);

    // 销毁旧元素并释放内存
    if (_start) {
        for (T* p = _start; p != _finish; ++p) {
            _alloc.destroy(p);
        }
        _alloc.deallocate(_start, oldCapacity);
    }

    _start = newStart;
    _finish = newFinish;
    _end_of_storage = _start + newCapacity;
}

template <typename Container>
void printCapacity(const Container &con) {
    cout << "size() = " << con.size() << endl;
    cout << "capacity() = " << con.capacity() << endl;
}

void test() {
    Vector<int> vec;
    printCapacity(vec);

    vec.push_back(1);
    printCapacity(vec);

    vec.push_back(2);
    printCapacity(vec);

    vec.push_back(3);
    printCapacity(vec);

    vec.push_back(4);
    printCapacity(vec);

    vec.push_back(5);
    printCapacity(vec);

    vec.push_back(6);
    printCapacity(vec);

    cout << "\nElements: ";
    for (auto elem : vec) {
        cout << elem << " ";
    }
    cout << endl;
}

int main() {
    test();
    return 0;
}
